package com.gtgj.widget.slice;

import com.gtgj.widget.ResourceTable;
import com.gtgj.widget.util.TextUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.webengine.*;
import ohos.agp.utils.TextTool;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.PixelMap;

public class WebAbilitySlice extends AbilitySlice {
    private WebView webView;
    private ProgressBar progressBar;
    private DatabaseHelper databaseHelper;
    private Preferences preferences;
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, WebAbilitySlice.class.getName());
    private String url = "https://h5.133.cn/gtgjwap/h5/ticketAgent/home?ptid=vivoscreen";
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_web);
        progressBar = findComponentById(ResourceTable.Id_progressBar);
        databaseHelper = new DatabaseHelper(getApplicationContext());
        preferences = databaseHelper.getPreferences(getBundleName());
        initWebview();
        getCookie();
        if (intent.hasEntity("url") && !TextUtils.isEmpty(intent.getStringParam("url"))) {
            url = intent.getStringParam("url");
        }
        webView.load(url);
    }

    private void initWebview(){
        webView = findComponentById(ResourceTable.Id_webview);
        WebConfig webSettings = webView.getWebConfig();
        webSettings.setJavaScriptPermit(true);
        webSettings.setWebStoragePermit(true);
        webSettings.setDataAbilityPermit(true);
        webSettings.setViewPortFitScreen(true);
        webView.setWebAgent(new WebAgent(){
            @Override
            public void onLoadingPage(WebView webView, String url, PixelMap icon) {
                super.onLoadingPage(webView, url, icon);

            }

            @Override
            public void onPageLoaded(WebView webView, String url) {
                super.onPageLoaded(webView, url);

            }
        });
        webView.setBrowserAgent(new BrowserAgent(this) {

            @Override
            public void onProgressUpdated(WebView webview, int newProgress) {
                super.onProgressUpdated(webview, newProgress);
                // 加载进度变更时自定义处理
                HiLog.debug(TAG, "progress is " + newProgress);
                if (progressBar != null) {
                    progressBar.setProgressValue(newProgress);
                    if (newProgress == 100) {
                        progressBar.setVisibility(Component.HIDE);
                    }
                }
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        super.onBackground();
        setCookie();
    }

    @Override
    protected void onStop() {
        setCookie();
        super.onStop();
    }

    @Override
    protected void onBackPressed() {
        if (webView != null && webView.getNavigator().canGoBack()) {
            webView.getNavigator().goBack();
        } else {
            super.onBackPressed();
        }
    }

    private void getCookie() {
        String cookie = preferences.getString("cookie", "");
        if (!TextTool.isNullOrEmpty(cookie)) {
            CookieStore cookieStore = CookieStore.getInstance();
            cookieStore.setCookieEnable(true);
            String[] cookieArray = cookie.split(";");// 多个Cookie是使用分号分隔的
            for (String s : cookieArray) {
                int position = s.indexOf("=");// 在Cookie中键值使用等号分隔
                String cookieName = s.substring(0, position);// 获取键
                String cookieValue = s.substring(position + 1);// 获取值
                String value = cookieName + "=" + cookieValue;// 键值对拼接成 value
                cookieStore.setCookie(url, value.trim());
            }
            cookieStore.persist();
        }
    }

    private void setCookie(){
        CookieStore cookieStore = CookieStore.getInstance();
        cookieStore.setCookieEnable(true);
        cookieStore.persist();
        String cookie = cookieStore.getCookie(url);
        preferences.putString("cookie", cookie);
        preferences.flushSync();
    }
}
